/**
 * 主应用逻辑
 * 处理页面路由、用户交互和业务逻辑
 */

class App {
    constructor() {
        this.currentUser = null;
        this.currentPage = 'dashboard';
        this.init();
    }

    /**
     * 初始化应用
     */
    init() {
        this.bindEvents();
        this.checkAuth();
        this.loadDashboardData();
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 登录表单
        const loginForm = document.getElementById('login-form');
        if (loginForm) {
            loginForm.addEventListener('submit', this.handleLogin.bind(this));
        }

        // 注册表单
        const registerForm = document.getElementById('register-form');
        if (registerForm) {
            registerForm.addEventListener('submit', this.handleRegister.bind(this));
        }

        // 页面切换链接
        const loginLink = document.getElementById('login-link');
        const registerLink = document.getElementById('register-link');
        if (loginLink) loginLink.addEventListener('click', () => this.showPage('login'));
        if (registerLink) registerLink.addEventListener('click', () => this.showPage('register'));

        // 侧边栏菜单
        const menuItems = document.querySelectorAll('.menu-item');
        menuItems.forEach(item => {
            item.addEventListener('click', () => {
                const page = item.dataset.page;
                this.showPage(page);
            });
        });

        // 退出登录
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', this.handleLogout.bind(this));
        }

        // 模态框关闭
        const modalClose = document.getElementById('modal-close');
        if (modalClose) {
            modalClose.addEventListener('click', Utils.hideModal);
        }

        // 绑定其他按钮事件
        this.bindButtonEvents();
    }

    /**
     * 绑定按钮事件
     */
    bindButtonEvents() {
        // 客户管理
        const addCustomerBtn = document.getElementById('add-customer-btn');
        if (addCustomerBtn) {
            addCustomerBtn.addEventListener('click', this.showAddCustomerModal.bind(this));
        }

        // 违约申请
        const newBreachBtn = document.getElementById('new-breach-btn');
        if (newBreachBtn) {
            newBreachBtn.addEventListener('click', this.showNewBreachModal.bind(this));
        }

        // 恢复申请
        const newRecoveryBtn = document.getElementById('new-recovery-btn');
        if (newRecoveryBtn) {
            newRecoveryBtn.addEventListener('click', this.showNewRecoveryModal.bind(this));
        }

        // 刷新按钮
        const refreshBreachRecords = document.getElementById('refresh-breach-records');
        const refreshRecoveryRecords = document.getElementById('refresh-recovery-records');
        if (refreshBreachRecords) {
            refreshBreachRecords.addEventListener('click', this.loadBreachRecords.bind(this));
        }
        if (refreshRecoveryRecords) {
            refreshRecoveryRecords.addEventListener('click', this.loadRecoveryRecords.bind(this));
        }

        // 筛选器
        const breachStatusFilter = document.getElementById('breach-status-filter');
        const recoveryStatusFilter = document.getElementById('recovery-status-filter');
        if (breachStatusFilter) {
            breachStatusFilter.addEventListener('change', this.loadBreachRecords.bind(this));
        }
        if (recoveryStatusFilter) {
            recoveryStatusFilter.addEventListener('change', this.loadRecoveryRecords.bind(this));
        }
    }

    /**
     * 检查用户认证状态
     */
    checkAuth() {
        const token = localStorage.getItem('token');
        if (token) {
            this.showPage('main');
            this.loadInitialData();
        } else {
            this.showPage('login');
        }
    }

    /**
     * 显示指定页面
     * @param {string} pageName - 页面名称
     */
    showPage(pageName) {
        // 处理登录/注册页面切换
        if (pageName === 'login' || pageName === 'register') {
            // 隐藏所有页面
            const pages = document.querySelectorAll('.page');
            pages.forEach(page => page.classList.remove('active'));

            // 显示目标页面
            const targetPage = document.getElementById(`${pageName}-page`);
            if (targetPage) {
                targetPage.classList.add('active');
            }
            return;
        }

        // 处理主应用页面切换
        if (pageName === 'main') {
            // 隐藏所有页面
            const pages = document.querySelectorAll('.page');
            pages.forEach(page => page.classList.remove('active'));

            // 显示主应用页面
            const mainPage = document.getElementById('main-page');
            if (mainPage) {
                mainPage.classList.add('active');
            }
            return;
        }

        // 处理主应用内的子页面切换
        // 隐藏所有页面内容
        const pageContents = document.querySelectorAll('.page-content');
        pageContents.forEach(content => content.classList.remove('active'));

        // 显示目标页面内容
        const targetContent = document.getElementById(`${pageName}-content`);
        if (targetContent) {
            targetContent.classList.add('active');
        }

        // 更新侧边栏菜单状态
        const menuItems = document.querySelectorAll('.menu-item');
        menuItems.forEach(item => {
            item.classList.remove('active');
            if (item.dataset.page === pageName) {
                item.classList.add('active');
            }
        });

        // 更新页面标题
        this.updatePageTitle(pageName);

        // 加载页面数据
        this.loadPageData(pageName);
    }

    /**
     * 更新页面标题
     * @param {string} pageName - 页面名称
     */
    updatePageTitle(pageName) {
        const titleMap = {
            'dashboard': '仪表盘',
            'customers': '客户管理',
            'breach-applications': '违约申请',
            'breach-records': '违约记录',
            'recovery-applications': '恢复申请',
            'recovery-records': '恢复记录',
            'settings': '系统设置'
        };

        const pageTitle = document.getElementById('page-title');
        if (pageTitle) {
            pageTitle.textContent = titleMap[pageName] || '未知页面';
        }
    }

    /**
     * 加载页面数据
     * @param {string} pageName - 页面名称
     */
    loadPageData(pageName) {
        switch (pageName) {
            case 'dashboard':
                this.loadDashboardData();
                break;
            case 'customers':
                this.loadCustomers();
                break;
            case 'breach-applications':
                this.loadBreachApplications();
                break;
            case 'breach-records':
                this.loadBreachRecords();
                break;
            case 'recovery-applications':
                this.loadRecoveryApplications();
                break;
            case 'recovery-records':
                this.loadRecoveryRecords();
                break;
            case 'settings':
                this.loadSettings();
                break;
        }
    }

    /**
     * 处理登录
     * @param {Event} event - 事件对象
     */
    async handleLogin(event) {
        event.preventDefault();
        
        const formData = Utils.getFormData('#login-form');
        const { username, password } = formData;

        if (!username || !password) {
            Utils.showToast('请输入用户名和密码', 'error');
            return;
        }

        Utils.showLoading();
        
        try {
            const result = await UserAPI.login(username, password);
            
            if (result.success) {
                Utils.showToast('登录成功', 'success');
                this.currentUser = username;
                this.showPage('main');
                this.loadInitialData();
            } else {
                Utils.showToast(result.message || '登录失败', 'error');
            }
        } catch (error) {
            Utils.showToast('登录失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 处理注册
     * @param {Event} event - 事件对象
     */
    async handleRegister(event) {
        event.preventDefault();
        
        const formData = Utils.getFormData('#register-form');
        const { username, password } = formData;

        if (!username || !password) {
            Utils.showToast('请输入用户名和密码', 'error');
            return;
        }

        if (username.length > 16 || password.length > 16) {
            Utils.showToast('用户名和密码不能超过16个字符', 'error');
            return;
        }

        Utils.showLoading();
        
        try {
            const result = await UserAPI.register(username, password);
            
            if (result.success) {
                Utils.showToast('注册成功，请登录', 'success');
                this.showPage('login');
                Utils.clearForm('#register-form');
            } else {
                Utils.showToast(result.message || '注册失败', 'error');
            }
        } catch (error) {
            Utils.showToast('注册失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 处理退出登录
     */
    handleLogout() {
        API.api.clearToken();
        this.currentUser = null;
        this.showPage('login');
        Utils.showToast('已退出登录', 'info');
    }

    /**
     * 加载初始数据
     */
    async loadInitialData() {
        await Promise.all([
            this.loadDashboardData(),
            this.loadCustomers(),
            this.loadBreachRecords(),
            this.loadRecoveryRecords()
        ]);
    }

    /**
     * 加载仪表盘数据
     */
    async loadDashboardData() {
        try {
            const [customersResult, breachResult, recoveryResult] = await Promise.all([
                BreachAPI.getCustomers(),
                BreachAPI.getBreachRecords(),
                RecoveryAPI.getRecoveryRecords()
            ]);

            // 更新统计数据
            const totalCustomers = customersResult.success ? customersResult.data.length : 0;
            const pendingBreaches = breachResult.success ? 
                breachResult.data.filter(record => record.审核状态 === '待审核').length : 0;
            const pendingRecoveries = recoveryResult.success ? 
                recoveryResult.data.filter(record => record.审核状态 === '待审核').length : 0;
            const completedToday = breachResult.success ? 
                breachResult.data.filter(record => {
                    const today = new Date().toDateString();
                    const recordDate = new Date(record.认定申请时间).toDateString();
                    return recordDate === today && record.审核状态 !== '待审核';
                }).length : 0;

            document.getElementById('total-customers').textContent = totalCustomers;
            document.getElementById('pending-breaches').textContent = pendingBreaches;
            document.getElementById('pending-recoveries').textContent = pendingRecoveries;
            document.getElementById('completed-today').textContent = completedToday;

        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
        }
    }

    /**
     * 加载客户列表
     */
    async loadCustomers() {
        try {
            const result = await BreachAPI.getCustomers();
            
            if (result.success) {
                this.renderCustomersTable(result.data);
            } else {
                Utils.showToast('加载客户列表失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载客户列表失败', 'error');
        }
    }

    /**
     * 渲染客户表格
     * @param {Array} customers - 客户数据
     */
    renderCustomersTable(customers) {
        const tbody = document.querySelector('#customers-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (customers.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="empty-state">暂无客户数据</td></tr>';
            return;
        }

        customers.forEach(customer => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${customer.客户号 || ''}</td>
                <td>${customer.客户名 || ''}</td>
                <td>${customer.性别 || ''}</td>
                <td>${customer.区域 || ''}</td>
                <td>${customer.行业 || ''}</td>
                <td>${customer.联系方式 || ''}</td>
                <td>${customer.集团 || ''}</td>
                <td>${Utils.getStatusBadge(customer.违约情况 === 1 ? '1' : '0')}</td>
                <td>
                    <div class="table-actions">
                        <button class="btn btn-sm btn-primary" onclick="app.showCustomerDetail('${customer.客户号}')">查看</button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 加载违约申请
     */
    async loadBreachApplications() {
        try {
            const result = await BreachAPI.getBreachRecords();
            
            if (result.success) {
                this.renderBreachApplicationsTable(result.data);
            } else {
                Utils.showToast('加载违约申请失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载违约申请失败', 'error');
        }
    }

    /**
     * 渲染违约申请表格
     * @param {Array} applications - 申请数据
     */
    renderBreachApplicationsTable(applications) {
        const tbody = document.querySelector('#breach-applications-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (applications.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="empty-state">暂无违约申请</td></tr>';
            return;
        }

        applications.forEach(app => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${app.违约审核编号 || ''}</td>
                <td>${app.客户号 || ''}</td>
                <td>${app.客户名 || ''}</td>
                <td>${app.违约原因 || ''}</td>
                <td>${app.严重程度 || ''}</td>
                <td>${app.外部最新等级 || ''}</td>
                <td>${Utils.formatDate(app.认定申请时间, 'YYYY-MM-DD HH:mm')}</td>
                <td>${Utils.getStatusBadge(app.审核状态)}</td>
                <td>
                    <div class="table-actions">
                        ${app.审核状态 === '待审核' ? 
                            `<button class="btn btn-sm btn-success" onclick="app.approveBreach('${app.违约审核编号}')">通过</button>
                             <button class="btn btn-sm btn-error" onclick="app.rejectBreach('${app.违约审核编号}')">拒绝</button>` :
                            `<button class="btn btn-sm btn-primary" onclick="app.showBreachDetail('${app.违约审核编号}')">查看</button>`
                        }
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 加载恢复申请
     */
    async loadRecoveryApplications() {
        try {
            const result = await RecoveryAPI.getRecoveryRecords();
            
            if (result.success) {
                this.renderRecoveryApplicationsTable(result.data);
            } else {
                Utils.showToast('加载恢复申请失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载恢复申请失败', 'error');
        }
    }

    /**
     * 渲染恢复申请表格
     * @param {Array} applications - 申请数据
     */
    renderRecoveryApplicationsTable(applications) {
        const tbody = document.querySelector('#recovery-applications-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (applications.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty-state">暂无恢复申请</td></tr>';
            return;
        }

        applications.forEach(app => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${app.重生审核编号 || ''}</td>
                <td>${app.违约审核编号 || ''}</td>
                <td>${app.客户号 || ''}</td>
                <td>${app.客户名 || ''}</td>
                <td>${app.重生原因 || ''}</td>
                <td>${Utils.formatDate(app.重生申请时间, 'YYYY-MM-DD HH:mm')}</td>
                <td>${Utils.getStatusBadge(app.审核状态)}</td>
                <td>
                    <div class="table-actions">
                        ${app.审核状态 === '待审核' ? 
                            `<button class="btn btn-sm btn-success" onclick="app.approveRecovery('${app.重生审核编号}')">通过</button>
                             <button class="btn btn-sm btn-error" onclick="app.rejectRecovery('${app.重生审核编号}')">拒绝</button>` :
                            `<button class="btn btn-sm btn-primary" onclick="app.showRecoveryDetail('${app.重生审核编号}')">查看</button>`
                        }
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 加载违约记录
     */
    async loadBreachRecords() {
        try {
            const statusFilter = document.getElementById('breach-status-filter');
            const status = statusFilter ? statusFilter.value : null;
            
            const result = await BreachAPI.getBreachRecords(status);
            
            if (result.success) {
                this.renderBreachRecordsTable(result.data);
            } else {
                Utils.showToast('加载违约记录失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载违约记录失败', 'error');
        }
    }

    /**
     * 渲染违约记录表格
     * @param {Array} records - 记录数据
     */
    renderBreachRecordsTable(records) {
        const tbody = document.querySelector('#breach-records-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (records.length === 0) {
            tbody.innerHTML = '<tr><td colspan="15" class="empty-state">暂无违约记录</td></tr>';
            return;
        }

        records.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.违约审核编号 || ''}</td>
                <td>${record.客户号 || ''}</td>
                <td>${record.客户名 || ''}</td>
                <td>${record.性别 || ''}</td>
                <td>${record.区域 || ''}</td>
                <td>${record.行业 || ''}</td>
                <td>${record.集团 || ''}</td>
                <td>${record.违约原因 || ''}</td>
                <td>${record.认定人 || ''}</td>
                <td>${Utils.formatDate(record.认定申请时间, 'YYYY-MM-DD HH:mm')}</td>
                <td>${record.严重程度 || ''}</td>
                <td>${record.外部最新等级 || ''}</td>
                <td>${record.备注 || ''}</td>
                <td>${Utils.getStatusBadge(record.审核状态)}</td>
                <td>
                    <div class="table-actions">
                        ${record.审核状态 === '待审核' ? 
                            `<button class="btn btn-sm btn-success" onclick="app.approveBreach('${record.违约审核编号}')">通过</button>
                             <button class="btn btn-sm btn-error" onclick="app.rejectBreach('${record.违约审核编号}')">拒绝</button>` :
                            `<button class="btn btn-sm btn-primary" onclick="app.showBreachDetail('${record.违约审核编号}')">查看</button>`
                        }
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 加载恢复记录
     */
    async loadRecoveryRecords() {
        try {
            const statusFilter = document.getElementById('recovery-status-filter');
            const status = statusFilter ? statusFilter.value : null;
            
            const result = await RecoveryAPI.getRecoveryRecords(status);
            
            if (result.success) {
                this.renderRecoveryRecordsTable(result.data);
            } else {
                Utils.showToast('加载恢复记录失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载恢复记录失败', 'error');
        }
    }

    /**
     * 渲染恢复记录表格
     * @param {Array} records - 记录数据
     */
    renderRecoveryRecordsTable(records) {
        const tbody = document.querySelector('#recovery-records-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (records.length === 0) {
            tbody.innerHTML = '<tr><td colspan="11" class="empty-state">暂无恢复记录</td></tr>';
            return;
        }

        records.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.重生审核编号 || ''}</td>
                <td>${record.客户号 || ''}</td>
                <td>${record.客户名 || ''}</td>
                <td>${record.违约原因 || ''}</td>
                <td>${record.严重程度 || ''}</td>
                <td>${record.外部最新等级 || ''}</td>
                <td>${record.认定人 || ''}</td>
                <td>${Utils.formatDate(record.认定申请时间, 'YYYY-MM-DD HH:mm')}</td>
                <td>${record.重生原因 || ''}</td>
                <td>${Utils.getStatusBadge(record.审核状态)}</td>
                <td>
                    <div class="table-actions">
                        ${record.审核状态 === '待审核' ? 
                            `<button class="btn btn-sm btn-success" onclick="app.approveRecovery('${record.重生审核编号}')">通过</button>
                             <button class="btn btn-sm btn-error" onclick="app.rejectRecovery('${record.重生审核编号}')">拒绝</button>` :
                            `<button class="btn btn-sm btn-primary" onclick="app.showRecoveryDetail('${record.重生审核编号}')">查看</button>`
                        }
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 显示新增客户模态框
     */
    showAddCustomerModal() {
        const content = `
            <form id="add-customer-form">
                <div class="form-group">
                    <label for="customer-id">客户号</label>
                    <input type="text" id="customer-id" name="customerId" required>
                </div>
                <div class="form-group">
                    <label for="customer-name">客户名</label>
                    <input type="text" id="customer-name" name="customerName" required>
                </div>
                <div class="form-group">
                    <label for="customer-gender">性别</label>
                    <select id="customer-gender" name="gender" required>
                        <option value="">请选择</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="customer-region">区域</label>
                    <input type="text" id="customer-region" name="region" required>
                </div>
                <div class="form-group">
                    <label for="customer-industry">行业</label>
                    <input type="text" id="customer-industry" name="industry" required>
                </div>
                <div class="form-group">
                    <label for="customer-phone">联系方式</label>
                    <input type="text" id="customer-phone" name="phone" required>
                </div>
                <div class="form-group">
                    <label for="customer-group">集团</label>
                    <input type="text" id="customer-group" name="group" required>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">添加客户</button>
                    <button type="button" class="btn btn-secondary" onclick="Utils.hideModal()">取消</button>
                </div>
            </form>
        `;

        Utils.showModal('新增客户', content, () => {
            const form = document.getElementById('add-customer-form');
            if (form) {
                form.addEventListener('submit', this.handleAddCustomer.bind(this));
            }
        });
    }

    /**
     * 处理新增客户
     * @param {Event} event - 事件对象
     */
    async handleAddCustomer(event) {
        event.preventDefault();
        
        const formData = Utils.getFormData('#add-customer-form');
        
        // 验证必填字段
        if (!formData.customerId || !formData.customerName || !formData.gender || 
            !formData.region || !formData.industry || !formData.phone || !formData.group) {
            Utils.showToast('请填写所有必填字段', 'error');
            return;
        }
        
        Utils.showLoading();
        
        try {
            const result = await BreachAPI.addCustomer(formData);
            
            if (result.success) {
                Utils.showToast('客户添加成功', 'success');
                Utils.hideModal();
                this.loadCustomers();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '添加失败', 'error');
            }
        } catch (error) {
            Utils.showToast('添加失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 显示新建违约申请模态框
     */
    async showNewBreachModal() {
        try {
            const [customersResult, reasonsResult] = await Promise.all([
                BreachAPI.getCustomers(),
                BreachAPI.getBreachReasons(1) // 只获取启用的原因
            ]);

            if (!customersResult.success || !reasonsResult.success) {
                Utils.showToast('加载数据失败', 'error');
                return;
            }

            const customers = customersResult.data;
            const reasons = reasonsResult.data;

            const content = `
                <form id="new-breach-form">
                    <div class="form-group">
                        <label for="breach-customer">客户</label>
                        <select id="breach-customer" name="customid" required>
                            <option value="">请选择客户</option>
                            ${customers.map(customer => 
                                `<option value="${customer.客户号}">${customer.客户名} (${customer.客户号})</option>`
                            ).join('')}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="breach-reason">违约原因</label>
                        <select id="breach-reason" name="reason" required>
                            <option value="">请选择违约原因</option>
                            ${reasons.map(reason => 
                                `<option value="${reason.违约原因编号}">${reason.违约原因}</option>`
                            ).join('')}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="breach-level">严重程度</label>
                        <select id="breach-level" name="dangerLevel" required>
                            <option value="">请选择严重程度</option>
                            <option value="1">轻微</option>
                            <option value="2">一般</option>
                            <option value="3">严重</option>
                            <option value="4">非常严重</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="breach-out-level">外部最新等级</label>
                        <input type="number" id="breach-out-level" name="outLevel" min="0" max="10" value="0">
                    </div>
                    <div class="form-group">
                        <label for="breach-info">备注</label>
                        <textarea id="breach-info" name="info" rows="3" placeholder="请输入备注信息"></textarea>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">提交申请</button>
                        <button type="button" class="btn btn-secondary" onclick="Utils.hideModal()">取消</button>
                    </div>
                </form>
            `;

            Utils.showModal('新建违约申请', content, () => {
                const form = document.getElementById('new-breach-form');
                if (form) {
                    form.addEventListener('submit', this.handleNewBreach.bind(this));
                }
            });

        } catch (error) {
            Utils.showToast('加载数据失败', 'error');
        }
    }

    /**
     * 处理新建违约申请
     * @param {Event} event - 事件对象
     */
    async handleNewBreach(event) {
        event.preventDefault();
        
        const formData = Utils.getFormData('#new-breach-form');
        
        Utils.showLoading();
        
        try {
            const result = await BreachAPI.submitBreachApplication(formData);
            
            if (result.success) {
                Utils.showToast('违约申请提交成功', 'success');
                Utils.hideModal();
                this.loadBreachRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '提交失败', 'error');
            }
        } catch (error) {
            Utils.showToast('提交失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 审核通过违约申请
     * @param {string} id - 申请ID
     */
    async approveBreach(id) {
        if (!confirm('确定要通过这个违约申请吗？')) return;
        
        Utils.showLoading();
        
        try {
            const result = await BreachAPI.verifyBreachApplication(id, '审核通过');
            
            if (result.success) {
                Utils.showToast('审核通过', 'success');
                this.loadBreachRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '审核失败', 'error');
            }
        } catch (error) {
            Utils.showToast('审核失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 审核拒绝违约申请
     * @param {string} id - 申请ID
     */
    async rejectBreach(id) {
        if (!confirm('确定要拒绝这个违约申请吗？')) return;
        
        Utils.showLoading();
        
        try {
            const result = await BreachAPI.verifyBreachApplication(id, '审核未通过');
            
            if (result.success) {
                Utils.showToast('审核拒绝', 'success');
                this.loadBreachRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '审核失败', 'error');
            }
        } catch (error) {
            Utils.showToast('审核失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 审核通过恢复申请
     * @param {string} id - 申请ID
     */
    async approveRecovery(id) {
        if (!confirm('确定要通过这个恢复申请吗？')) return;
        
        Utils.showLoading();
        
        try {
            const result = await RecoveryAPI.verifyRecoveryApplication(id, '审核通过');
            
            if (result.success) {
                Utils.showToast('审核通过', 'success');
                this.loadRecoveryRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '审核失败', 'error');
            }
        } catch (error) {
            Utils.showToast('审核失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 审核拒绝恢复申请
     * @param {string} id - 申请ID
     */
    async rejectRecovery(id) {
        if (!confirm('确定要拒绝这个恢复申请吗？')) return;
        
        Utils.showLoading();
        
        try {
            const result = await RecoveryAPI.verifyRecoveryApplication(id, '审核未通过');
            
            if (result.success) {
                Utils.showToast('审核拒绝', 'success');
                this.loadRecoveryRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '审核失败', 'error');
            }
        } catch (error) {
            Utils.showToast('审核失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 加载设置页面数据
     */
    async loadSettings() {
        try {
            const result = await BreachAPI.getBreachReasons();
            
            if (result.success) {
                this.renderBreachReasonsTable(result.data);
            } else {
                Utils.showToast('加载违约原因失败: ' + result.message, 'error');
            }
        } catch (error) {
            Utils.showToast('加载设置数据失败', 'error');
        }
    }

    /**
     * 渲染违约原因表格
     * @param {Array} reasons - 原因数据
     */
    renderBreachReasonsTable(reasons) {
        const tbody = document.querySelector('#breach-reasons-table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';

        if (reasons.length === 0) {
            tbody.innerHTML = '<tr><td colspan="4" class="empty-state">暂无违约原因</td></tr>';
            return;
        }

        reasons.forEach(reason => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${reason.违约原因编号 || ''}</td>
                <td>${reason.违约原因 || ''}</td>
                <td>${Utils.getStatusBadge(reason.是否启用)}</td>
                <td>
                    <div class="table-actions">
                        <button class="btn btn-sm ${reason.是否启用 == 1 ? 'btn-warning' : 'btn-success'}" 
                                onclick="app.toggleBreachReason('${reason.违约原因编号}', ${reason.是否启用 == 1 ? 0 : 1})">
                            ${reason.是否启用 == 1 ? '禁用' : '启用'}
                        </button>
                    </div>
                </td>
            `;
            tbody.appendChild(row);
        });
    }

    /**
     * 显示客户详情
     * @param {string} customerId - 客户ID
     */
    showCustomerDetail(customerId) {
        Utils.showToast(`查看客户详情: ${customerId}`, 'info');
    }

    /**
     * 显示违约详情
     * @param {string} breachId - 违约ID
     */
    showBreachDetail(breachId) {
        Utils.showToast(`查看违约详情: ${breachId}`, 'info');
    }

    /**
     * 显示恢复详情
     * @param {string} recoveryId - 恢复ID
     */
    showRecoveryDetail(recoveryId) {
        Utils.showToast(`查看恢复详情: ${recoveryId}`, 'info');
    }

    /**
     * 显示新建恢复申请模态框
     */
    async showNewRecoveryModal() {
        try {
            const [breachResult, reasonsResult] = await Promise.all([
                BreachAPI.getBreachRecords('审核通过'),
                RecoveryAPI.getRecoveryReasons()
            ]);

            if (!breachResult.success || !reasonsResult.success) {
                Utils.showToast('加载数据失败', 'error');
                return;
            }

            const breaches = breachResult.data;
            const reasons = reasonsResult.data;

            const content = `
                <form id="new-recovery-form">
                    <div class="form-group">
                        <label for="recovery-breach">违约申请</label>
                        <select id="recovery-breach" name="id" required>
                            <option value="">请选择违约申请</option>
                            ${breaches.map(breach => 
                                `<option value="${breach.违约审核编号}">${breach.客户名} - ${breach.违约原因}</option>`
                            ).join('')}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="recovery-reason">恢复原因</label>
                        <select id="recovery-reason" name="reasonid" required>
                            <option value="">请选择恢复原因</option>
                            ${reasons.map(reason => 
                                `<option value="${reason.重生原因编号}">${reason.重生原因}</option>`
                            ).join('')}
                        </select>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">提交申请</button>
                        <button type="button" class="btn btn-secondary" onclick="Utils.hideModal()">取消</button>
                    </div>
                </form>
            `;

            Utils.showModal('新建恢复申请', content, () => {
                const form = document.getElementById('new-recovery-form');
                if (form) {
                    form.addEventListener('submit', this.handleNewRecovery.bind(this));
                }
            });

        } catch (error) {
            Utils.showToast('加载数据失败', 'error');
        }
    }

    /**
     * 处理新建恢复申请
     * @param {Event} event - 事件对象
     */
    async handleNewRecovery(event) {
        event.preventDefault();
        
        const formData = Utils.getFormData('#new-recovery-form');
        
        Utils.showLoading();
        
        try {
            const result = await RecoveryAPI.submitRecoveryApplication(formData);
            
            if (result.success) {
                Utils.showToast('恢复申请提交成功', 'success');
                Utils.hideModal();
                this.loadRecoveryRecords();
                this.loadDashboardData();
            } else {
                Utils.showToast(result.message || '提交失败', 'error');
            }
        } catch (error) {
            Utils.showToast('提交失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }

    /**
     * 切换违约原因状态
     * @param {string} reasonid - 原因ID
     * @param {number} enable - 是否启用
     */
    async toggleBreachReason(reasonid, enable) {
        Utils.showLoading();
        
        try {
            const result = await BreachAPI.changeBreachReasonStatus(reasonid, enable);
            
            if (result.success) {
                Utils.showToast(enable ? '已启用' : '已禁用', 'success');
                this.loadSettings();
            } else {
                Utils.showToast(result.message || '操作失败', 'error');
            }
        } catch (error) {
            Utils.showToast('操作失败，请检查网络连接', 'error');
        } finally {
            Utils.hideLoading();
        }
    }
}

// 初始化应用
let app;
document.addEventListener('DOMContentLoaded', () => {
    app = new App();
});

